﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace ZXthex.Html
{
    public class CSSStyleSheet
    {
        I_CSSRule[] ruleset;
        public void LoadFrom(HtmlDocument doc)
        {
            string css_text = "";
            for (int i = 0; i < doc.Head.ChildCount; i++)
            {
                if (doc.Head.GetChild(i).Name.ToLower() == "style")
                {
                    css_text = doc.Head.GetChild(i).InnerText;
                    break;
                }
            }

            using (var nc = NextChars.FromString(css_text))
            {
                BuildCSS(nc);
            }
        }

        void BuildCSS(NextChars reader)
        {
            CSSStyleSheetBuilder.Default.LoadCSS(reader, out ruleset);
        }

        public CSS_Declaration[] GetSuitableDeclarations(ReadOnlyHtmlNode node)
        {
            List<CSS_Declaration> res_list = new List<CSS_Declaration>(8);

            for (int i = 0; i < ruleset.Length; i++)
            {
                if (ruleset[i].Match(node))
                {
                    res_list.AddRange(ruleset[i].GetDeclarations());
                }
            }


            return res_list.ToArray();
        }
    }
}